package com.rams.jhms.gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.rams.jhms.Config;
import com.rams.jhms.gui.components.BtnGetPath;
import com.rams.jhms.gui.components.FileSelector;

import net.miginfocom.layout.AC;
import net.miginfocom.layout.CC;
import net.miginfocom.layout.LC;
import net.miginfocom.swing.MigLayout;

public class ApplicationSettingsForm extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8930622988916201661L;

	private JPanel mainPanel = new JPanel();
	private JLabel mediaDbPath = new JLabel(Config.local.settingsMediaDbPath());
	private JTextField txtMediaDbPath = new JTextField();
	private BtnGetPath getMediaDbPath = new BtnGetPath();
	
	private JButton btnSave = new JButton(Config.local.btnSave());
	private JButton btnClose = new JButton(Config.local.btnClose());
	
	private ApplicationSettingsForm instance;
	
	public ApplicationSettingsForm() {
		super();
		instance = this;
		this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		this.setModal(true);
		
		MigLayout ml = new MigLayout(new LC().debug(Config.layoutDebug).noGrid(),
									 new AC().grow(100, 1).fill(1, 1).align("right", 2));
		mainPanel.setLayout(ml);
		
		getMediaDbPath.addActionListener(new BtnsActionListener());

		btnSave.setActionCommand("btn_save");
		btnSave.addActionListener(new BtnsActionListener());
		
		
		mainPanel.add(mediaDbPath);
		mainPanel.add(txtMediaDbPath, new CC().growX());
		mainPanel.add(getMediaDbPath);
		mainPanel.add(btnSave, new CC().alignX("right").alignY("bottom").newline());
		
		this.setContentPane(mainPanel);
		this.setMinimumSize(new Dimension(400, 270));
		this.setResizable(false);

		this.pack();
		this.setLocationRelativeTo(null);
		
		initData();
	}
	
	private void initData() {
		if (Config.mediaDbPath != null)
			txtMediaDbPath.setText(Config.mediaDbPath);
	}

	private class BtnsActionListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			String command = e.getActionCommand();
			if (command.equals(BtnGetPath.btn_command)) {
				File f = FileSelector.selectFolder(instance, "");
				txtMediaDbPath.setText(f.getPath());
				return;
			} else if("btn_save".equals(command)) {
				Config.mediaDbPath = txtMediaDbPath.getText();
				Config.save();
			}
		}
	}
}
